# 多智能体任务分配与资源共享算法实现

class Agent:
    def __init__(self, id, capabilities, resources):
        self.id = id
        self.capabilities = capabilities
        self.resources = resources
        self.tasks = []

class Task:
    def __init__(self, id, priority, required_capabilities, required_resources):
        self.id = id
        self.priority = priority
        self.required_capabilities = required_capabilities
        self.required_resources = required_resources

class System:
    def __init__(self, agents, tasks, total_resources):
        self.agents = agents
        self.tasks = tasks
        self.total_resources = total_resources

    def allocate_tasks(self):
        # 按任务优先级排序
        self.tasks.sort(key=lambda t: t.priority, reverse=True)

        for task in self.tasks:
            suitable_agents = [agent for agent in self.agents if set(task.required_capabilities).issubset(agent.capabilities)]
            
            if suitable_agents:
                # 选择任务负载最小的智能体
                best_agent = min(suitable_agents, key=lambda a: len(a.tasks))
                best_agent.tasks.append(task)
                else:
                    print(f"Task {task.id} could not be allocated due to lack of suitable agents.")

    def simulate_agent_failure(self, failed_agent_id):
        failed_agent = next((agent for agent in self.agents if agent.id == failed_agent_id), None)
        if failed_agent:
            print(f"Agent {failed_agent_id} has failed. Reassigning its tasks.")
            for task in failed_agent.tasks:
                suitable_agents = [agent for agent in self.agents if agent.id != failed_agent_id and set(task.required_capabilities).issubset(agent.capabilities)]
                if suitable_agents:
                    best_agent = min(suitable_agents, key=lambda a: len(a.tasks))
                    if allocated < amount:
                        print(f"Resource {resource} for Task {task.id} partially allocated: {allocated}/{amount}")
                    best_agent.tasks.append(task)
                    print(f"Task {task.id} reassigned to Agent {best_agent.id}.")
                else:
                    print(f"Task {task.id} could not be reassigned due to lack of suitable agents.")
            failed_agent.tasks = []
        else:
            print(f"Agent {failed_agent_id} not found.")
                else:
                    print(f"Task {task.id} could not be allocated due to lack of suitable agents.")

    def share_resources(self):
        for task in self.tasks:
            allocated_resources = {}

            for resource, amount in task.required_resources.items():
                if resource in self.total_resources:
                    available = self.total_resources[resource]
                    allocated = min(available, amount)  # 分配资源，优先满足需求
                    self.total_resources[resource] -= allocated
                    allocated_resources[resource] = allocated

            task.allocated_resources = allocated_resources
# 测试代码
if __name__ == "__main__":
    agents = [
        Agent(1, {"A", "B"}, {"R1": 10, "R2": 5}),
        Agent(2, {"B", "C"}, {"R1": 8, "R2": 7}),
    ]
    tasks = [
        Task(1, 10, {"A"}, {"R1": 5}),
        Task(2, 8, {"B"}, {"R2": 6}),
        Task(3, 5, {"C"}, {"R1": 4}),
    ]
    total_resources = {"R1": 20, "R2": 15}

    system = System(agents, tasks, total_resources)
    system.allocate_tasks()
    system.share_resources()

    # 模拟智能体故障
    system.simulate_agent_failure(1)

    # 显示结果
    system.display_results()
    for agent in system.agents:
        print(f"Agent {agent.id} Tasks: {[task.id for task in agent.tasks]}")
    print(f"Remaining Resources: {system.total_resources}")
        for agent in system.agents:
            log_file.write(f"Agent {agent.id} Tasks: {[task.id for task in agent.tasks]}\n")
        log_file.write(f"Remaining Resources: {system.total_resources}\n")

    def display_results(self):
        for agent in self.agents:
            print(f"Agent {agent.id}:\nTasks: {[task.id for task in agent.tasks]}\n")
        print(f"Remaining Resources: {self.total_resources}\n")

# 示例使用
agents = [
    Agent(1, {"A", "B"}, {"R1": 10, "R2": 5}),
    Agent(2, {"B", "C"}, {"R1": 8, "R2": 7}),
]
tasks = [
    Task(1, 10, {"A"}, {"R1": 5}),
    Task(2, 8, {"B"}, {"R2": 6}),
    Task(3, 5, {"C"}, {"R1": 4}),
]
total_resources = {"R1": 20, "R2": 15}

system = System(agents, tasks, total_resources)
system.allocate_tasks()
system.share_resources()
system.display_results()